<template>
  <div class="new_div1 display">
    <el-card class="box-card">
      <template #header>
        <div class="customerTitle1">
          <div>
            <span><span class="leve_title" >寄售结算单</span>
<!--             <div class="add_order_font1">
           <span>
             <span>
               单据号：
             </span>
             <span>
               {{'BD-DYJ-202307220021'}}
             </span>
           </span>
            <span>
             <span class="add_order_font2">
               订单状态：
             </span>
             <span >
               {{'创建中'}}
             </span>
           </span>
              <span class="add_order_font2">销售员：{{'XXX'}}部门-{{'XXX'}} </span>
           </div>-->
            </span>
          </div>
          <div >
            <el-button
              @click="back"
            >
              {{'返回'}}
            </el-button>
            <el-button
              class="customerButton1"
              plain
              type="primary"
              @click="share_save(form_new_date,0)"
            >
              暂存
            </el-button>
            <el-button
              class="customerButton1"
              plain
              type="primary"
              @click="share_save(form_new_date,1)"
            >
              保存
            </el-button>
            <el-button  type="primary" @click="share_save(form_new_date,2)">
              提交
            </el-button>
          </div>
        </div>
      </template>
      <div>
        <VabStep :active="active" :steps="arr_approve"/>
      </div>
    </el-card>
    <div>
      <el-card class="box-card">
        <template #header>
          <span class="titleHead1">
            订单信息
          </span>
        </template>
        <div>
          <el-form
            label-width="105px"
            ref="form_new_date"
            :model="form_new_list"
            :rules="rules"
          >
            <el-row :gutter="24">
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="客户" prop="customer_uid">
                  <VabSelectForm @change='customerChange' :clearable="false"  v-model="form_new_list.customer_uid" :options="customer_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="销售组织" prop="sales_org_id">
                  <VabSelectForm @change="changeSelect"  :clearable="false"  v-model="form_new_list.sales_org_id" :options="sales_org_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="价目表" prop="price_list_uid">
                  <el-select
                    filterable
                    v-model="form_new_list.price_list_uid"
                    class="width_100"
                    placeholder="请选择"
                    @change="priceChange"
                  >
                    <el-option v-for="item in price_list" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="寄售仓库" prop="consignment_warehouse_no">
                  <el-select
                    filterable
                    v-model="form_new_list.consignment_warehouse_no"
                    class="width_100"
                    placeholder="请选择"
                    @change="consignmentWarehouseChang(form_new_list.consignment_warehouse_no)"
                  >
                    <el-option v-for="item in consignmentWarehouseList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
<!--              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="期望运输方式" prop="transport_type">
                  <el-select
                    filterable
                    v-model="form_new_list.transport_type"
                    class="width_100"
                    placeholder="请选择"
                  >
                    <el-option v-for="item in transport_type_list" :key="item.value"  :label="item.label" :value="item.value">
                      <span style="float: left" >{{ item.label }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="联系人" prop="contact_user">
                  <el-input
                    v-model="form_new_list.contact_user"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="联系电话" prop="contact_tel">
                  <el-input
                    v-model="form_new_list.contact_tel"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16" style="padding-right: 0px">
                <el-form-item label="收货地址" prop="shipping_address" style="width: 100%;display: flex;justify-content: space-between" >
                  <el-cascader
                    ref="address_ref"
                    v-model="form_new_list.shipping_address"
                    :options="areaOption"
                    style="width:42%;display: inline-block"
                    :props="{ value: 'name', label: 'name' }"
                  >
                    <template #default="{ data }">
                      <span>{{ data.name }}</span>
                    </template>
                  </el-cascader>
                  <el-input
                    v-model="form_new_list.address"
                    class="inputAddress"
                    style="width: calc(57% - 15px) "
                    placeholder="详细地址"
                  >
                    <template #append >
                      &lt;!&ndash;                    <span @click="openAddress" >
                                            地址簿
                                          </span>&ndash;&gt;
                      <el-button size="small" @click="openAddress" >地址簿 </el-button>
                    </template>
                  </el-input>
                  &lt;!&ndash;                <el-button style="width: 100%" size="small" type="primary" @click="openAddress" >地址簿 </el-button>&ndash;&gt;
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="运费付款方式" prop="payment_type">
                  <VabSelectForm  :clearable="false"  v-model="form_new_list.payment_type" :options="payment_type_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="期望送达时间" prop="delivery_time">
                  <el-date-picker
                    v-model="form_new_list.delivery_time"
                    type="date"
                    :clearable="false"
                    style="width: 100%"
                    placeholder="请选择时间"
                  />
                </el-form-item>
              </el-col>-->
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="结算币别" prop="trading_curr_id">
                  <VabSelectForm   :clearable="false"  v-model="form_new_list.trading_curr_id" :options="currency"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
                <el-form-item label="开票类型" prop="invoice_type">
                  <VabSelectForm :clearable="false"  v-model="form_new_list.invoice_type" :options="invoice_type_list"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="16" :xl="8">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="form_new_list.remark"
                    autosize
                    type="textarea"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>
    </div>
    <el-card>
      <template #header>
          <span class="titleHead1">
            产品信息
          </span>
      </template>
      <ConsignProducts ref="products_ref" v-model:copyProductList="copyProductList" v-model:copyProductNumber="copyProductNumber" />
    </el-card>
<!--    <OrderLog ref="orderLog" />-->
    <Address ref="addressSon" />
<!--    <AuditInformation />
    <OrderLog ref="orderLog" />-->
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import AuditInformation from '/@/views/order_management/component/AuditInformation.vue'
import OrderLog from '/@/views/order_management/component/OrderLog.vue'
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import { customer_info, customer_optionsList, customerPriceList } from "/@/api/dms/customer";
import { organization_list } from "/@/api/dms/organization";
import { options_list, optionsCreate } from "/@/api/dms/options";
import Address from '../../component/Address.vue'
import ConsignProducts from '../../consignOrder/component/ConsignProducts.vue'
import { flattenArray, productFields } from "/@/views/order_management/orderText";
import lodash from "lodash";
import { orderInfo, orderInsert } from "/@/api/dms/order";
import { areaOptions } from "/@/views/corpManagement/corpCustomers/tools";
import router from "/@/router";
import { getInventoryConsginStockList } from "/@/api/dms/inventory";
import { DateFormat } from "/@/utils/utils";
defineOptions({
    name: 'AddStatement',
  })
const orderLog = ref<any>(null)
const route:any = useRoute()
const arr_approve = ref([
  { title: '寄售结算单', active: true, path:`/order/addStatement`},
  { title: '销售出库单', active: false, path:`` },
])
const active = ref(1)
const form_new_list = ref<any>({
  customer_name:'',
  //客户id
  customer_uid:'',
  //客户编码
  customer_number:'',
  // 价目表
  price_list_uid:'',
  // 折扣表
  discount_uid:'',
  //运输方式
  transport_type:'',
  //费用结算方式
  payment_type:'',
  //备注
  remark:'',
  //销售组织
  sales_org_id:'', //币别
  trading_curr_id:'',
  // 开票类型
  invoice_type:'',
  consignment_warehouse_no:'',////寄售出库
})
const rules = ref<FormRules<any>>({
  price_list_uid: [{ required: true, message: '请选择价目表', trigger: 'change' }],
  sales_org_id: [{ required: true, message: '请选择销售组织', trigger: 'change' }],
  customer_uid: [{ required: true, message: '请选择客户', trigger: 'change' }],
  trading_curr_id: [{ required: true, message: '请选择币别', trigger: 'change' }],
  invoice_type: [{ required: true, message: '请选择开票类型', trigger: 'change' }],
  consignment_warehouse_no:[{ required: true, message: '请选择寄售仓库', trigger: 'change' }],////寄售仓库
})
const form_new_date = ref<any>(null)
// 获取组
const getGroupList = ref<any>(undefined)
// 获取列表信息 复制使用
const copyList = ref<any>(undefined)
//复制数据暂存
const copyProductList = ref(undefined)
// 复制总数数据
const copyProductNumber = ref<any>(undefined)
const customerNumber = ref<any>(undefined)
// **********选择框的内容***********
const customer_list = ref([])
let price_list  = ref<any>([])
const discount_list = ref([{value:'折扣表',label:'折扣表'}])
const sales_org_list = ref([])
const transport_type_list = ref<any>([])
const payment_type_list =ref([{value:'1',label:'运费到付'},{value:'2',label:'运费预付'}])
// 地址
const address_ref =ref<any>(null)
const areaOption = ref<any>([])
// 财务信息
let currency = ref([])
let invoice_type_list = ref([])
// ******地址簿*******
const addressSon =ref<any>({})
const openAddress = ()=>{
  if(form_new_list.value.customer_uid != '' && form_new_list.value.customer_uid ){
    addressSon.value.dialogVisibles = true
    addressSon.value.customerId = form_new_list.value.customer_uid
    addressSon.value.selectAddress = undefined
  }else {
    ElMessage.warning(`客户不能为空，请先选择客户`)
  }

}
const transport = (va:any)=>{
  ElMessageBox.prompt(' ', '添加运输方式', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    center: true,
    /*inputPattern:
      /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,*/
    inputErrorMessage: 'Invalid Email',
  })
    .then(({ value }) => {
      optionsCreate({label:value.trim(),level:2,module:'transport_type',module_name:'运输方式',sort:50}).then((data:any)=>{
        if(data.code == 200){
          options_list({module:'transport_type',level:2}).then((data:any)=>{
            if(data.code == 200){
              ElMessage.success(`提交成功`)
              const arr = data.data.map((item:any)=> {return {value:item.uid , label:item.name}})
              transport_type_list.value = arr
            }
          })
        }
      })
    })
}
// *****表单客户更改********
const customerChange = (value:any)=>{
  const data:any = customer_list.value?.filter((item:any)=>{return item.value == value})[0]
  customerNumber.value= data.number
  customer_info({uid:value}).then((data:any)=>{
    const getAddress = data.data.location?.filter((i:any)=>i.is_default_consignee == 1)[0] || undefined
    form_new_list.value = {
      ...form_new_list.value,
      // 价目表
      price_list_uid:'',
      // 折扣表
      discount_uid:'',
      //运输方式
      transport_type:'',
      //费用结算方式
      payment_type:'',
      //备注
      remark:'',
      //销售组织
      sales_org_id:'',
      //币别
      trading_curr_id:data.data.trading_curr_id || '',
      // 开票类型
      invoice_type:data.data.invoice_type || ''
    }
  })
  copyProductNumber.value = form_new_list.value
  products_ref.value.productList = [productFields]
}
//****** 产品信息**********
const products_ref=ref<any>(undefined)
// *********按钮***************
const check = ()=>{
  const product_list = flattenArray(products_ref.value.productList)
  const  check1 =  product_list.map((item:any,index:any)=>{
    if(item.goods_no == '' || item.goods_no == undefined){
      ElMessage.warning(`序号为 ${index +1}产品编码 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check2 =  product_list.map((item:any,index:any)=>{
    if(item.goods_name == '' || item.goods_name == undefined){
      ElMessage.warning(`序号为 ${index +1}产品名称 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check3 =  product_list.map((item:any,index:any)=>{
    if(item.goods_type == '' || item.goods_type == undefined){
      ElMessage.warning(`序号为 ${index +1}产品类型 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check4 =  product_list.map((item:any,index:any)=>{
    if(item.sales_num == '' || item.sales_num == undefined || item.sales_num == 0){
      ElMessage.warning(`序号为 ${index +1}销售数量 不能为0`)
      return false
    }else {
      if( item.batch_usable_num < item.sales_num ){
        ElMessage.warning(`序号为 ${index +1}预计可发量 小于 销售数量`)
        return false
      }else {
        return true
      }

    }
  })
  /*const  check5 =  product_list.map((item:any,index:any)=>{
    if(item.warehouse_no == '' || item.warehouse_no == undefined){
      ElMessage.warning(`序号为 ${index +1}仓库 不能为空`)
      return false
    }else {
      return true
    }
  })*/
  const  check8 =  product_list.map((item:any,index:any)=>{
    if(item.tax_rate == '' || item.tax_rate == undefined){
      ElMessage.warning(`序号为 ${index +1}税率 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check9 =  product_list.map((item:any,index:any)=>{
    if(item.sales_unit == '' || item.sales_unit == undefined){
      ElMessage.warning(`序号为 ${index +1}销售单位 不能为空`)
      return false
    }else {
      return true
    }
  })
  const  check7 =  product_list.map((item:any,index:any)=>{
    if(item.goods_type !== '赠品'&& item.goods_type !== '样品'){
      if( item.order_price == '' || item.order_price == 0){
        ElMessage.warning(`序号为 ${index +1}含税单价 不能为空`)
        return false
      }else if(item.including_tax_price  != item.price ){
        if(item.price_remark =='' || item.price_remark == undefined){
          ElMessage.warning(`序号为 ${index +1}改价原因 不能为空`)
          return false
        }else {
          return true
        }
      }else {
        return true
      }
    }else {
      return true
    }
  })
  const check6 = [...check1,...check2,...check3,...check4,...check8,...check9,...check7].every(i=>i==true)
  return check6
}
const share_save = lodash.debounce( async (va:any,statuse:number)=>{
  const product_list = flattenArray(products_ref.value.productList)
  const product_many = products_ref.value.products_number?.reduce((obj:any, item:any) => {
    obj[item.item] = item.value;
    return obj;
  }, {})
  const product_check = check()
  await va.validate((valid: any, fields: any) => {
    if (valid) {
      if(product_check) {
        orderInsert({
          ...form_new_list.value,
          consignment_warehouse_name:consignmentWarehouseName(form_new_list.value.consignment_warehouse_no),
          ...product_many,
          trade_from:'员工',
          detail:[...product_list],
          type:5,
          status :statuse}).then((data:any)=>{
          if(data.code == 200){
            ElMessage.success(`提交成功`)
            va.resetFields()
            products_ref.value.productList =[]
            products_ref.value.products_number = []
            copyList.value=undefined
            customerNumber.value = undefined
            addressSon.value.selectAddress= []
            router.push(`/order/consignment`)
          }
        })
      }
    }
  })
},500)
const share_cancel = (formEl:any)=>{
  formEl.resetFields()
  customerNumber.value = undefined
  products_ref.value.productList =[]
  products_ref.value.products_number = []
  copyList.value=undefined
  addressSon.value.selectAddress= []
}
//获取客户
const getCustomer=async ()=>{
  // 客户
  await customer_optionsList({is_group:2,name:''}).then((data:any)=>{
    if(data.code == 200){
      customer_list.value = data.data.map((item:any)=> {return {value:item.uid, label:item.name,number:item.number}})
    }
  })
  // 组织
  await  organization_list({}).then((data:any)=>{
    if(data.code == 200){
      sales_org_list.value = data.data.map((item:any)=> {return {value:item.uid , label:item.name}})
    }
  })
  // 运输方式
  await options_list({module:'transport_type',level:2}).then((data:any)=>{
    if(data.code == 200){
      const arr = data.data.map((item:any)=> {return {value:item.uid , label:item.name}})
      //[...arr,{value:-1 , label:'自定义',display:true}]
      transport_type_list.value = arr
    }
  })
  options_list({module:'currency'}).then((data:any)=>{
    // console.log(data,'币别')
    if(data.code == 200){
      currency.value = data.data?.map((i:any)=>{return {value:i.uid,label:i.name}}) || []
    }else {
      currency.value=[]
    }
  })
  options_list({module:'invoice_type'}).then((data:any)=>{
    // console.log(data,'币别')
    if(data.code == 200){
      invoice_type_list.value = data.data?.map((i:any)=>{return {value:i.uid,label:i.name}}) || []
    }else {
      invoice_type_list.value=[]
    }
  })
  // 寄售订单
  getInventoryConsginStockList({}).then((data:any)=>{
    if(data.code == 200){
      consignmentWarehouseList.value = data.data.list.map((va:any)=>{return {value:va.key,label:va.label}})
    }
  })
}
//获取下拉框值
const changeSelect =(va:string,value:any)=>{
  form_new_list.value = {
    ...form_new_list.value,
    // 价目表
    price_list_uid:'',
  }
  copyProductNumber.value = form_new_list.value
  products_ref.value.productList = [productFields]
}
//价目表下拉框
const priceChange = ()=>{
  copyProductNumber.value = form_new_list.value
  products_ref.value.productList = [productFields]
}
//寄售仓库
const consignmentWarehouseList = ref<any>([])
const consignmentWarehouseChang = (value:any)=>{
  copyProductNumber.value = form_new_list.value
}
const back = ()=>{
  router.push(`/order/consignment`)
}
// 监听
watchEffect(()=>{
  const {selectAddress} = addressSon.value  || []
  if(selectAddress && selectAddress.length > 0 ){
    form_new_list.value.contact_user= selectAddress[0].shipping_contact,
      form_new_list.value.contact_tel =  selectAddress[0].shipping_tel
    form_new_list.value.shipping_address = selectAddress[0].shipping_address,
      form_new_list.value.address = selectAddress[0].address
  }
  if(customerNumber.value && form_new_list.value.sales_org_id != ''){
    customerPriceList({page:1,limit:1000,type:2,filter:{use_org_id:form_new_list.value.sales_org_id,customer_number:customerNumber.value}}).then((data:any)=>{
      if(data.code == 200){
        price_list.value = data.data.list.map((i:any)=>{return {value:i.id,label:i.name}})
      }
    })
  }else {
    price_list.value = []
  }
})
const consignmentWarehouseName = (value:any)=>{
  if(value){
    return  consignmentWarehouseList.value?.filter((va:any)=> va.value == value)[0]?.label || ''
  }else {
    return ''
  }

}
watchEffect(()=>{
  if(products_ref.value){
    products_ref.value.componentType = 2
  }
})
const getOrderInfo = ()=>{
  if(route.query.id){

    // orderLog.value._getCustomerPriceLog(route.query.id)
    orderInfo({uid:route.query.id}).then((data:any)=>{
      if(data.code === 200){
        const ba:any = customer_list.value?.filter((item:any)=>{return item.value == data.data.customer_uid})[0]
        customerNumber.value= ba.number
       /* const data:any = customer_list.value?.filter((item:any)=>{return item.value == data.data.customer_uid})[0]
        customerNumber.value= data.number
        console.log(data);*/
        customerPriceList({page:1,limit:1000,type:2,filter:{use_org_id:data.data.sales_org_id,customer_number:customerNumber.value}}).then((data:any)=>{
          if(data.code == 200){
            price_list.value = data.data.list.map((i:any)=>{return {value:i.id,label:i.name}})
          }
        })
        const orderList = data.data
        form_new_list.value = {
          trading_curr_id:orderList.trading_curr_id,
          invoice_type:orderList.invoice_type,
          sales_org_id:orderList.sales_org_id,
          remark:orderList.remark,
          customer_uid:orderList.customer_uid,
          price_list_uid:Number(orderList.price_list_uid),
          discount_uid:orderList.discount_uid,
          transport_type:orderList.transport_type,
          payment_type:orderList.payment_type,
          uid:orderList.uid,
          consignment_warehouse_no:orderList.consignment_warehouse_no,
        }
        products_ref.value.productList = orderList.detail
        copyProductNumber.value = orderList
      }
    })
  }
}
onMounted(async ()=>{
  // 获取地址
  areaOption.value = await areaOptions()
  //获取客户
  getCustomer()
  getOrderInfo()

})
</script>

<style lang="scss" scoped>
@import "../../index";
.constItem{
  :deep(){
    .el-form-item{
      margin-bottom: 2px;
    }
  }
  .button{
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-bottom: 2px;
  }
}
.border{
  margin-bottom: 10px;
  border-top: 1px solid #bdbdbd;
  border-radius: 0px;
}
.inputAddress{
  margin-left:10px;
  margin-right:10px;
  :deep(){
    .el-input__wrapper{
      width: 100%;
    }
    .el-input-group__append{
      background-color:var(--el-color-primary);
      color: #fff;
      box-shadow: 0 0px 0 0var(--el-color-primary)
    }
  }
}
</style>

